package com.dxtx.util;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;

public class CircleImageDrawable extends Drawable {

    private Paint mPaint;
    private int mRange;
    private Bitmap mBitmap;

    private float mDrawablePadding;


    public CircleImageDrawable(Bitmap bitmap) {
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
                Shader.TileMode.CLAMP);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setShader(bitmapShader);
        mRange = Math.min(bitmap.getWidth(), bitmap.getHeight());

        //获取centerCrop的源位置,长宽不统一则放弃一部分
        Rect src;
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        if (w == h) {
            src = new Rect(0, 0, w, h);
        } else if (w > h) {
            src = new Rect((w - h) / 2, 0, (w + h) / 2, h);
        } else {
            src = new Rect(0, (h - w) / 2, w, (w + h) / 2);
        }
        mBitmap = Bitmap.createBitmap(bitmap, src.left, src.top, src.width(), src.height());
    }

    public CircleImageDrawable(Bitmap bitmap, float drawablePadding) {
        this(bitmap);
        this.mDrawablePadding = drawablePadding;
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.drawCircle(mRange / 2, mRange / 2, mRange / 2, mPaint);
    }

    @Override
    public int getIntrinsicWidth() {
        return mRange;
    }

    @Override
    public int getIntrinsicHeight() {
        return mRange;
    }

    @Override
    public void setAlpha(int alpha) {
        mPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        mPaint.setColorFilter(cf);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

}
